package com.lanmaoly.demo;

import java.io.*;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.text.DateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;

public class Test2 {

    public static void method1(File f, Random random) {
        FileWriter fw = null;
        try {
            fw = new FileWriter(f, true);
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
        PrintWriter pw = new PrintWriter(fw);
//        int temp = 100000000;
        int temp = 100000;
        for (int i = 0; i < temp; i++) {
            pw.println(random.nextInt(temp));
            pw.flush();
        }
        try {
            fw.flush();
            pw.close();
            fw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //    public static void main(String[] args) {
//        String words [] = {"yes" ,"an" ,"go"};
//        for(String word:words){
//            System.out.println(word.hashCode());
//            int temp = hash(word.toCharArray());
//            System.out.println(temp);
//        }
//    }
    static int HASHLEN = 1000;

    public static int hash(char[] word) {
        int index = 0;
        int i = 0;
        while (i < word.length) {
            index += index * 31 + word[i];
            i++;
        }
        return index % HASHLEN;
    }

    public static void main(String[] args) throws Exception {
        Thread thread1 = new Thread(() -> {
            String filePath = "D:/set/largefile1.txt";
            File file = new File(filePath);
            Random random = new Random();
            method1(file, random);
        });
        Thread thread2 = new Thread(() -> {
            String filePath = "D:/set/largefile2.txt";
            File file = new File(filePath);
            Random random = new Random();
            method1(file, random);
        });
        thread1.start();
        thread2.start();
        thread1.join();
        thread2.join();
        System.out.println("------------");
//        cut("", 10);
//        String filePath = "D:/split/test.txt";
//        String filePath = "D:/split/qwe.txt";
//        File file = new File(filePath);
//        Random random = new Random();
//        method1(file, random);
//        cut(filePath, 100);
//        BufferedReader reader = new BufferedReader(new FileReader(filePath));
//        // 读取一行
//        String line = reader.readLine();
//        while (null != line) {
//            // 计算hash
//            final int hash = hash(line.toCharArray());
//            System.out.println(hash);
//            // 保存文件
//            File file = new File("D:/split/hash/" + hash + ".txt");
//            if (file.exists()) {
//                boolean newFile = file.createNewFile();
//            }
//            FileWriter fw = new FileWriter(file, true);
//            PrintWriter pw = new PrintWriter(fw);
//            pw.println(line);
//            pw.flush();
//            fw.flush();
//            fw.close();
//            pw.close();
//            // 读取一行
//            line = reader.readLine();
//        }
//        reader.close();
    }

    /**
     * 分割文件
     *
     * @param filePath 要分割的文件路径
     * @param num      要分割成多少份
     * @author shandowF
     * @date 2016年3月2日
     */
    public static void cut(String filePath, int num) {
        File file = new File(filePath);
        long lon = file.length() / num;
        // +1L
        try {
            RandomAccessFile raf1 = new RandomAccessFile(file, "r");
            // 值设置越小，则各个文件的字节数越接近平均值，但效率会降低，这里折中，取1024
            byte[] bytes = new byte[1024];
            int len = -1;
            for (int i = 0; i < num; i++) {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                String name = getFileBegin(filePath) + getYYMMDD() + "-" + i + getFileSuff(filePath);
                System.out.println(name);
                File file2 = new File(name);
                RandomAccessFile raf2 = new RandomAccessFile(file2, "rw");
                while ((len = raf1.read(bytes)) != -1) {
                    // 读到文件末尾时，len返回-1，结束循环
                    raf2.write(bytes, 0, len);
                    if (raf2.length() > lon) {
                        // 当生成的新文件字节数大于lon时，结束循环
                        break;
                    }
                }
                raf2.close();
            }
            raf1.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 恢复文件
     *
     * @author shandowF
     * @date 2016年3月5日
     */
    public static void merge(String nowFilePath, String oldFilePath, int num) {
        File file = new File(nowFilePath);
        try {
// 写出文件
            RandomAccessFile target = new RandomAccessFile(file, "rw");
            for (int i = 0; i < num; i++) {
                String oldFile = getFileBegin(oldFilePath) + getYYMMDD() + i + getFileSuff(oldFilePath);
                File file2 = new File(oldFile);
                RandomAccessFile src = new RandomAccessFile(file2, "r");
                byte[] bytes = new byte[1024];// 每次读取字节数
                int len = -1;
                while ((len = src.read(bytes)) != -1) {
                    target.write(bytes, 0, len);// 循环赋值
                }
                src.close();
            }
            target.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 清洗文件让文件中没有重复的值
     *
     * @author shandowF
     * @date 2016年3月5日
     */
    public static void clear(File file, String newPath) {
        try {
            BufferedInputStream fis = new BufferedInputStream(new FileInputStream(file));
            // 用5M的缓冲读取文本文件
            BufferedReader buffer = new BufferedReader(new InputStreamReader(fis, "utf-8"), 20 * 1024 * 1024);
            OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(new File(newPath)), "utf-8");
            Set<String> set = new HashSet<>();
            // 临时字符串
            String temp = "";
            int x = 0;
            // 读文件,一行读一个
            while ((temp = buffer.readLine()) != null) {
                // 存储到Set集合里面
                set.add(temp);
                if (x % 30000 == 0) {
                    // System.out.print("..");
                }
                x++;
            }
            fis.close();
            buffer.close();
            for (String xxser : set) {
                out.write(xxser + "\r\n");
            }
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 获取文件除后缀名外的名字
     *
     * @author shandowF
     * @date 2016年3月5日
     */
    public static String getFileBegin(String filePath) {
        String i = getFileSuff(filePath);
        int index = filePath.indexOf(i);
        return filePath.substring(0, index);
    }


    /**
     * 获取文件后缀名
     *
     * @author shandowF
     * @date 2016年3月5日
     */
    public static String getFileSuff(String filePath) {
        int start = filePath.indexOf(".");
        int end = filePath.length();
        return filePath.substring(start, end);
    }

    ;


    /**
     * 获取当天 yy-mm-dd
     *
     * @return
     */
    public static String getYYMMDD() {
        DateFormat dateInstance = DateFormat.getDateInstance();
        return dateInstance.format(new Date());
    }

    /**
     * 判断两个文件是否相等
     *
     * @author shandowF
     * @date 2016年3月5日
     */
    public static String getFileMD5(File file) {
        if (!file.isFile()) {
            return null;
        }
        MessageDigest digest = null;
        FileInputStream in = null;
        byte buffer[] = new byte[8192];
        int len;
        try {
            digest = MessageDigest.getInstance("MD5");
            in = new FileInputStream(file);
            while ((len = in.read(buffer)) != -1) {
                digest.update(buffer, 0, len);
            }
            BigInteger bigInt = new BigInteger(1, digest.digest());
            return bigInt.toString(16);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                in.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
